<?php

require_once WACT_ROOT . '/db/db.inc.php';
require_once APP_ROOT.'model/common/utils.php';
require_once APP_ROOT.'model/common/site.php';


class Rotation {

    function insertItem(&$data) {
        $site_id = Site::getSiteID();
    	$data->set('site_id',$site_id);
        $Record =& DBC::NewRecord($data);
        return $Record->insertId('sport_rotation',
            array('headline','image', 'url', 'priority', 'site_id','alt','source','script'), 'id');
    }

    function &getRecord($id) {
        return DBC::FindRecord("SELECT R.*
        FROM sport_rotation R
        WHERE R.id = ". DBC::makeLiteral($id));
    }

    function updateItem($id, &$data) {
        $site_id = Site::getSiteID();
    	$data->set('site_id',$site_id);
        $Record =& DBC::NewRecord($data);
        $Record->update('sport_rotation',
            array('headline', 'image', 'url', 'priority', 'site_id','alt','source','script'),
            "id=". DBC::makeLiteral($id));
    }


    function delete($id) {
        DBC::execute("DELETE FROM sport_rotation WHERE id=". DBC::makeLiteral($id));
    }

     function &getRotationList(&$Pager, &$request) {
     	$site_id = Site::getSiteID();
     	$sql = "select R.*
     	from sport_rotation R
        where 1=1 ".Rotation::getFilter($request)."
        and R.site_id = ".DBC::makeLiteral($site_id)." ".
     	" order by ".Rotation::getOrder($request);
     	//print $sql;
        return DBC::NewPagedRecordSet($sql, $Pager);
     }

     function getFilter(&$request) {
      	$where = '';
      	return $where;
      }

      function getOrder(&$request) {
      	$sortby = 'R.id';

      	return $sortby;
      }

      function &getTotalPriority() {
        $site_id = Site::getSiteID();
		$query="select sum(priority) sump from sport_rotation where
		site_id = ".DBC::makeLiteral($site_id)." ";
		$sum = DBC::getOneValue($query);
		//print 'Sum '.$sum;
		return $sum;
      }


      function &getRandomRecord() {
        $sum =& Rotation::getTotalPriority();

      	$site_id = Site::getSiteID();
		$query="select R.id, R.headline, R.image, R.url, R.priority, R.alt, R.site_id, R.source, R.script from sport_rotation R where
        R.site_id = ".DBC::makeLiteral($site_id)." ";

		$rs =& DBC::NewRecordSet($query);
		$mycount = $rs->getTotalRowCount();

		//print "My Count:".$mycount;

		//print 'Sum '.$sum;
		$number=rand(0,$sum-1);
		//print 'Number '.$number;
		$rs->reset();


		$i=0;
		if($mycount>1) {
			while($rs->next() && $i<$number) {
				$ds = $rs->export();
                $priority = $rs->get('priority');
                //print 'Priority '.$priority;
				$i += $priority;
			}
            //print_r($ds);
			return $ds;
		} else if ($mycount==1) {
			$rs->next();
            $ds = $rs->export();
            //print_r($ds);
			return $ds;
        }
		else return null;


	}
}

?>
